---
title: "API Reference"
description: "Complete API documentation for MCP server framework"
icon: "book"
---

# API Reference

This document provides a complete reference for the `mcp-use/server` API, including all classes, methods, and type definitions.

## Server Creation

### `MCPServer` Class

Creates a new MCP server instance with Express integration.

```typescript
class MCPServer {
  constructor(config: ServerConfig): McpServerInstance
}
```

**Parameters:**
- `config` (ServerConfig) - Server configuration object (name is required in config)

**Returns:** `McpServerInstance` - Server instance with both MCP and Express methods

**Example:**
```typescript
// Basic usage
const server = new MCPServer({
  name: 'my-server',
  version: '1.0.0',
  description: 'My MCP server'
})

// With custom host (e.g., for Docker or remote access)
const server = new MCPServer({
  name: 'my-server',
  version: '1.0.0',
  host: '0.0.0.0' // or 'myserver.com'
})

// With full base URL (e.g., behind a proxy or custom domain)
const server = new MCPServer({
  name: 'my-server',
  version: '1.0.0',
  baseUrl: 'https://myserver.com' // or process.env.MCP_URL
})

// Production with explicit allowed origins
const server = new MCPServer({
  name: 'my-server',
  version: '1.0.0',
  allowedOrigins: [
    'https://myapp.com',
    'https://app.myapp.com'
  ]
})
```

**Note:** The `createMCPServer()` factory function is still available for backward compatibility, but the class constructor is recommended for new code.

## Server Configuration

### `ServerConfig`

Configuration object for server initialization.

```typescript
interface ServerConfig {
  name: string        // Server name
  version: string     // Server version (semver format)
  description?: string // Optional description
  host?: string       // Hostname for widget URLs and server endpoints (defaults to 'localhost')
  baseUrl?: string    // Full base URL (e.g., 'https://myserver.com') - overrides host:port for widget URLs
  allowedOrigins?: string[] // Allowed origins for DNS rebinding protection
  sessionIdleTimeoutMs?: number // Idle timeout for sessions in milliseconds (default: 300000 = 5 minutes)
  autoCreateSessionOnInvalidId?: boolean // Auto-create session on invalid ID (default: true, compatible with ChatGPT)
}
```

**`allowedOrigins` Configuration:**

The `allowedOrigins` option controls DNS rebinding protection behavior:

- **Development mode** (NODE_ENV !== "production"):
  - If not set: All origins are allowed (DNS rebinding protection disabled)
  - This enables direct browser connections from any origin for easier development

- **Production mode** (NODE_ENV === "production"):
  - If not set: DNS rebinding protection is disabled (not recommended for production)
  - If set to empty array: DNS rebinding protection is disabled
  - If set with origins: DNS rebinding protection is enabled with those specific origins

**Example:**
```typescript
// Development: No need to set (allows all origins)
const server = new MCPServer({
  name: 'my-server',
  version: '1.0.0'
})

// Production: Explicitly set allowed origins
const server = new MCPServer({
  name: 'my-server',
  version: '1.0.0',
  allowedOrigins: [
    'https://myapp.com',
    'https://app.myapp.com'
  ]
})
```

**`autoCreateSessionOnInvalidId` Configuration:**

The `autoCreateSessionOnInvalidId` option controls behavior when a client sends a request with an invalid or expired session ID:

- **Default: `true`** (compatible with ChatGPT and other non-compliant clients)
  - Server automatically creates a new session when invalid session ID is detected
  - Allows seamless reconnection after server restarts
  - Recommended for most use cases, especially when using ChatGPT or other OpenAI clients

- **When set to `false`**:
  - Server returns HTTP 404 Not Found for invalid session IDs (MCP protocol spec compliant)
  - Clients must explicitly send a new `initialize` request
  - Use only if you're certain all clients properly handle 404 errors by reinitializing

**Note**: According to the [MCP protocol specification](https://modelcontextprotocol.io/specification/2025-11-25/basic/transports#session-management), clients **MUST** start a new session by sending a new `InitializeRequest` when they receive HTTP 404 in response to a request containing an `MCP-Session-Id`. However, some clients (like ChatGPT) don't properly implement this behavior.

**Example:**
```typescript
// Default behavior (compatible with ChatGPT)
const server = new MCPServer({
  name: 'my-server',
  version: '1.0.0',
  autoCreateSessionOnInvalidId: true  // Default: true
})

// Strict MCP spec compliance (requires compliant clients)
const server = new MCPServer({
  name: 'my-server',
  version: '1.0.0',
  autoCreateSessionOnInvalidId: false  // Strict spec compliance
})
```

## Core Server Methods

### `server.tool()`

Registers a tool that clients can invoke.

```typescript
tool(definition: ToolDefinition): this
```

**Parameters:**
- `definition` (ToolDefinition) - Tool configuration and handler

**Returns:** Server instance for method chaining

**Example:**
```typescript
server.tool({
  name: 'calculate',
  description: 'Perform calculations',
  inputs: [
    { name: 'expression', type: 'string', required: true }
  ],
  cb: async ({ expression }) => {
    const result = eval(expression) // Note: Use safe evaluation in production
    return {
      content: [{
        type: 'text',
        text: `Result: ${result}`
      }]
    }
  }
})
```

### `server.resource()`

Registers a static resource that clients can read.

```typescript
resource(definition: ResourceDefinition): this
```

**Parameters:**
- `definition` (ResourceDefinition) - Resource configuration and content

**Returns:** Server instance for method chaining

**Example:**
```typescript
server.resource({
  name: 'config',
  uri: 'config://settings',
  title: 'Configuration',
  mimeType: 'application/json',
  description: 'Server configuration',
  annotations: {
    audience: ['user', 'assistant'],
    priority: 0.8
  },
  readCallback: async () => ({
    contents: [{
      uri: 'config://settings',
      mimeType: 'application/json',
      text: JSON.stringify({ theme: 'dark' })
    }]
  })
})
```

### `server.resourceTemplate()`

Registers a dynamic resource template with parameters.

```typescript
resourceTemplate(definition: ResourceTemplateDefinition): this
```

**Parameters:**
- `definition` (ResourceTemplateDefinition) - Template configuration

**Returns:** Server instance for method chaining

**Example:**
```typescript
server.resourceTemplate({
  name: 'user_profile',
  resourceTemplate: {
    uriTemplate: 'user://{userId}/profile',
    name: 'User Profile',
    mimeType: 'application/json',
    description: 'User profile data'
  },
  readCallback: async (uri, params) => ({
    contents: [{
      uri: uri.toString(),
      mimeType: 'application/json',
      text: JSON.stringify({
        userId: params.userId,
        name: 'John Doe'
      })
    }]
  })
})
```

### `server.prompt()`

Registers a prompt template for AI models.

```typescript
prompt(definition: PromptDefinition): this
```

**Parameters:**
- `definition` (PromptDefinition) - Prompt configuration and generator

**Returns:** Server instance for method chaining

**Example:**
```typescript
server.prompt({
  name: 'code_review',
  description: 'Generate code review prompt',
  args: [
    { name: 'language', type: 'string', required: true },
    { name: 'focus', type: 'string', required: false }
  ],
  cb: async ({ language, focus = 'general' }) => ({
    messages: [
      {
        role: 'system',
        content: 'You are a code reviewer.'
      },
      {
        role: 'user',
        content: `Review this ${language} code focusing on ${focus}.`
      }
    ]
  })
})
```

### `server.uiResource()`

Registers a UI widget as both a tool and resource.

```typescript
uiResource(definition: UIResourceDefinition): this
```

**Parameters:**
- `definition` (UIResourceDefinition) - UI widget configuration

**Returns:** Server instance for method chaining

**Example:**
```typescript
server.uiResource({
  type: 'externalUrl',
  name: 'dashboard',
  widget: 'analytics-dashboard',
  title: 'Analytics Dashboard',
  description: 'Interactive analytics visualization',
  props: {
    timeRange: {
      type: 'string',
      description: 'Time range for data',
      required: false,
      default: '7d'
    }
  },
  size: ['800px', '600px']
})
```

### `server.listen()`

Starts the HTTP server with MCP endpoints.

```typescript
listen(port?: number): Promise<void>
```

**Parameters:**
- `port` (number, optional) - Port to listen on (default: 3000)

**Returns:** Promise that resolves when server is listening

**Example:**
```typescript
await server.listen(8080)
console.log('Server running on port 8080')
```

## Type Definitions

### `ToolDefinition`

Configuration for tools.

```typescript
interface ToolDefinition {
  name: string                    // Unique tool identifier
  title?: string                  // Display title
  description?: string            // Tool description
  inputs?: InputDefinition[]      // Input parameters
  cb: ToolCallback               // Handler function
  annotations?: ToolAnnotations   // Optional annotations
  _meta?: Record<string, unknown> // Metadata (e.g., Apps SDK)
}

type ToolCallback = (params: Record<string, any>) => Promise<CallToolResult>
```

### `ResourceDefinition`

Configuration for static resources.

```typescript
interface ResourceDefinition {
  name: string                        // Resource identifier
  uri: string                        // Resource URI
  title?: string                     // Display title
  description?: string               // Resource description
  mimeType: string                   // MIME type
  annotations?: ResourceAnnotations  // Optional annotations
  readCallback: ReadResourceCallback // Content provider
}

type ReadResourceCallback = () => Promise<{
  contents: Array<{
    uri: string
    mimeType: string
    text?: string
    blob?: string
  }>
}>
```

### `ResourceTemplateDefinition`

Configuration for dynamic resource templates.

```typescript
interface ResourceTemplateDefinition {
  name: string                              // Template identifier
  title?: string                           // Display title
  description?: string                     // Template description
  annotations?: ResourceAnnotations        // Optional annotations
  resourceTemplate: ResourceTemplateConfig // Template configuration
  readCallback: ReadResourceTemplateCallback // Dynamic content provider
}

interface ResourceTemplateConfig {
  uriTemplate: string     // URI template with {params}
  name?: string          // Template name
  description?: string   // Template description
  mimeType?: string     // MIME type
}

type ReadResourceTemplateCallback = (
  uri: URL,
  params: Record<string, string>
) => Promise<ReadResourceResult>
```

### `PromptDefinition`

Configuration for prompt templates.

```typescript
interface PromptDefinition {
  name: string                // Prompt identifier
  title?: string             // Display title
  description?: string       // Prompt description
  args?: InputDefinition[]   // Arguments
  cb: PromptCallback        // Prompt generator
}

type PromptCallback = (args: Record<string, any>) => Promise<{
  messages: Array<{
    role: 'system' | 'user' | 'assistant'
    content: string
  }>
}>
```

### `UIResourceDefinition`

Configuration for UI widgets.

```typescript
interface UIResourceDefinition {
  // Resource identification
  name: string                    // Resource name
  title?: string                 // Display title
  description?: string           // Description

  // UI type configuration
  type: 'externalUrl' | 'rawHtml' | 'remoteDom' | 'appsSdk'

  // Widget-specific fields
  widget?: string               // Widget identifier (for externalUrl)
  htmlTemplate?: string        // HTML template (for appsSdk)
  htmlString?: string         // Raw HTML (for rawHtml)
  remoteDomFramework?: RemoteDomFramework // For remoteDom
  remoteDomCode?: string      // JavaScript code (for remoteDom)

  // Configuration
  props?: WidgetProps         // Widget properties
  size?: [string, string]    // [width, height]
  annotations?: ResourceAnnotations

  // Apps SDK specific
  appsSdkMetadata?: AppsSdkMetadata
}
```

### `InputDefinition`

Parameter definition for tools and prompts.

```typescript
interface InputDefinition {
  name: string         // Parameter name
  type: 'string' | 'number' | 'boolean' | 'object' | 'array'
  description?: string // Parameter description
  required?: boolean   // Is required (default: false)
  default?: any       // Default value
}
```

### `ResourceAnnotations`

Metadata annotations for resources.

```typescript
interface ResourceAnnotations {
  audience?: ('user' | 'assistant')[] // Target audience
  priority?: number                    // 0.0 to 1.0
  lastModified?: string               // ISO 8601 timestamp
}
```

### `WidgetProps`

Property definitions for UI widgets.

```typescript
type WidgetProps = Record<string, {
  type: 'string' | 'number' | 'boolean' | 'object' | 'array'
  description?: string
  required?: boolean
  default?: any
}>
```

### `AppsSdkMetadata`

OpenAI Apps SDK metadata for widgets.

```typescript
interface AppsSdkMetadata {
  'openai/widgetDescription'?: string
  'openai/widgetCSP'?: {
    connect_domains?: string[]
    resource_domains?: string[]
  }
  'openai/toolInvocation/invoking'?: string
  'openai/toolInvocation/invoked'?: string
  'openai/widgetAccessible'?: boolean
  'openai/resultCanProduceWidget'?: boolean
  [key: string]: unknown
}
```

## Express Integration

The server instance proxies all Express methods, allowing you to use Express functionality directly:

### Common Express Methods

```typescript
// HTTP route handlers
server.get(path, ...handlers)
server.post(path, ...handlers)
server.put(path, ...handlers)
server.delete(path, ...handlers)
server.patch(path, ...handlers)

// Middleware
server.use(...middleware)

// Static files
server.use('/static', express.static('public'))

// Route parameters
server.param(name, callback)

// Settings
server.set(setting, value)
server.get(setting)
```

### Example Express Usage

```typescript
import express from 'express'

// Body parsing middleware
server.use(express.json())
server.use(express.urlencoded({ extended: true }))

// Custom middleware
server.use((req, res, next) => {
  console.log(`${req.method} ${req.path}`)
  next()
})

// API routes
server.get('/api/status', (req, res) => {
  res.json({ status: 'ok' })
})

// Error handling
server.use((err, req, res, next) => {
  console.error(err.stack)
  res.status(500).send('Something broke!')
})
```

## Return Types

### `CallToolResult`

Tool execution result.

```typescript
interface CallToolResult {
  content: Array<{
    type: 'text' | 'image' | 'resource'
    text?: string
    data?: string
    mimeType?: string
  }>
  _meta?: Record<string, unknown>
}
```

### `ReadResourceResult`

Resource read result.

```typescript
interface ReadResourceResult {
  contents: Array<{
    uri: string
    mimeType: string
    text?: string
    blob?: string
  }>
}
```

### `PromptResult`

Prompt generation result.

```typescript
interface PromptResult {
  messages: Array<{
    role: 'system' | 'user' | 'assistant'
    content: string
  }>
}
```

## Utility Functions

### UI Resource Helpers

The framework provides utility functions for creating UI resources:

```typescript
import {
  buildWidgetUrl,
  createExternalUrlResource,
  createRawHtmlResource,
  createRemoteDomResource,
  createUIResourceFromDefinition
} from 'mcp-use/server'

// Build widget URL with parameters
const url = buildWidgetUrl('dashboard',
  { timeRange: '7d' },
  { baseUrl: 'http://localhost', port: 3000 }
)

// Create UI resource objects
const externalResource = createExternalUrlResource(
  'ui://widget/dashboard',
  'http://localhost:3000/widgets/dashboard',
  'text'
)
```

## Error Handling

The framework handles errors gracefully:

```typescript
server.tool({
  name: 'risky_operation',
  cb: async (params) => {
    try {
      // Perform operation
      const result = await riskyOperation(params)
      return {
        content: [{
          type: 'text',
          text: `Success: ${result}`
        }]
      }
    } catch (error) {
      // Return error as text content
      return {
        content: [{
          type: 'text',
          text: `Error: ${error.message}`
        }]
      }
    }
  }
})
```

## Best Practices

1. **Use TypeScript** - Leverage type safety for better development experience
2. **Handle Errors** - Always handle errors gracefully in callbacks
3. **Validate Input** - Validate parameters in tool callbacks
4. **Use Annotations** - Provide metadata for better client integration
5. **Chain Methods** - Use fluent API for cleaner code
6. **Document Tools** - Provide clear descriptions for all tools and resources

## React Components & Hooks

The `mcp-use/react` package provides React components and hooks for building OpenAI Apps SDK widgets.

### Components

#### `McpUseProvider`

Unified provider component that combines all common React setup.

```typescript
import { McpUseProvider } from 'mcp-use/react';

<McpUseProvider 
  debugger={boolean}
  viewControls={boolean | "pip" | "fullscreen"}
  autoSize={boolean}
>
  {children}
</McpUseProvider>
```

See [McpUseProvider documentation](./widget-components/mcpuseprovider) for details.

#### `WidgetControls`

Wrapper component that adds control buttons for widget debugging and view controls.

```typescript
import { WidgetControls } from 'mcp-use/react';

<WidgetControls 
  debugger={boolean}
  viewControls={boolean | "pip" | "fullscreen"}
  position="top-right"
>
  {children}
</WidgetControls>
```

See [WidgetControls documentation](./widget-components/widgetcontrols) for details.

#### `ErrorBoundary`

Error boundary component for graceful error handling.

```typescript
import { ErrorBoundary } from 'mcp-use/react';

<ErrorBoundary>
  {children}
</ErrorBoundary>
```

See [ErrorBoundary documentation](./widget-components/errorboundary) for details.

#### `Image`

Image component that handles both data URLs and public file paths.

```typescript
import { Image } from 'mcp-use/react';

<Image src="/fruits/apple.png" alt="Apple" />
```

See [Image documentation](./widget-components/image) for details.

#### `ThemeProvider`

Theme provider for consistent theme management.

```typescript
import { ThemeProvider } from 'mcp-use/react';

<ThemeProvider>
  {children}
</ThemeProvider>
```

See [ThemeProvider documentation](./widget-components/themeprovider) for details.

### Hooks

#### `useWidget<TProps, TOutput, TMetadata, TState>`

Main hook providing type-safe access to all widget capabilities.

```typescript
import { useWidget } from 'mcp-use/react';

const {
  props,
  output,
  metadata,
  state,
  setState,
  theme,
  displayMode,
  callTool,
  sendFollowUpMessage,
  openExternal,
  requestDisplayMode,
  notifyIntrinsicHeight,
  isAvailable,
} = useWidget<TProps, TOutput, TMetadata, TState>();
```

See [useWidget documentation](./widget-components/usewidget) for complete API reference.

#### `useWidgetProps<TProps>`

Get only the widget props.

```typescript
import { useWidgetProps } from 'mcp-use/react';

const props = useWidgetProps<{ city: string }>();
```

#### `useWidgetTheme()`

Get only the theme value.

```typescript
import { useWidgetTheme } from 'mcp-use/react';

const theme = useWidgetTheme(); // 'light' | 'dark'
```

#### `useWidgetState<TState>`

Get state management (state and setState).

```typescript
import { useWidgetState } from 'mcp-use/react';

const [state, setState] = useWidgetState<string[]>([]);
```

### Type Exports

```typescript
import type {
  UseMcpOptions,
  UseMcpResult,
  UseWidgetResult,
  Theme,
  DisplayMode,
  SafeArea,
  UserAgent,
  CallToolResponse,
} from 'mcp-use/react';
```

## Next Steps

- [Tools Guide](./tools) - Advanced tool patterns
- [Resources Guide](./resources) - Resource management
- [UI Widgets](./ui-widgets) - Building interactive widgets
- [Widget Components](./widget-components/mcpuseprovider) - React components reference
- [Examples](./examples) - Real-world implementations